package com.wft.design.gateway.receiver;

import com.wft.design.common.core.constant.GlobalExchange;
import com.wft.design.gateway.channel.DynamicRouteChannel;
import com.wft.design.gateway.support.DynamicRouteDefinitionRepository;
import com.wft.design.system.entity.SysGatewayRoute;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @author WFT
 * @date 2020/2/5
 * description: 动态路由消费逻辑
 */
@Slf4j
@Component
@RequiredArgsConstructor
@EnableBinding(value = DynamicRouteChannel.class)
public class DynamicRouteReceiver {

    private final DynamicRouteDefinitionRepository routeDefinitionRepository;


    /**
     * 监听路由被删除
     * @param routeId 路由Id
     */
    @StreamListener(value = GlobalExchange.DYNAMIC_ROUTE, condition = "headers['method']=='delete'")
    public void listenerDelete(String routeId){
        this.routeDefinitionRepository.delete(Mono.just(routeId)).subscribe();
    }

    /**
     * 新增或修改路由信息
     * @param route 路由信息
     */
    @StreamListener(value = GlobalExchange.DYNAMIC_ROUTE, condition = "headers['method']=='edit'")
    public void listenerEdit(SysGatewayRoute route){
        //  构建路由对象
        RouteDefinition definition = this.routeDefinitionRepository.build(route);
        if (null != definition) {
            //  保存路由信息
            this.routeDefinitionRepository.save(Mono.just(definition)).subscribe();
        }
    }

}
